import { useEffect, useState } from 'react'

import { companionCompanyListApi } from '@/api/pcs/pcsCompanionCompany'
import { createNursingWorkersApi, getNursingWorkersApi, updateNursingWorkersApi } from '@/api/pcs/pcsNursingWorkers'
import { queryOrgTreeApi } from '@/api/sys/organization'
import AekDrawer, { PromiseThen } from '@/components/AekDrawer'
import AekForm from '@/components/AekForm'
import AekLinkButton from '@/components/AekLinkButton'
import AekUpload from '@/components/AekUpload'
import APanel from '@/components/APanel'
import { REGEXP_CMB_DEBIT } from '@/utils/constants'
import {
  PCS_COMPANION_TYPE_ENUM,
  PCS_COMPANION_WAY_ENUM,
  PCS_NURSINGCREDENTIAL_ENUM,
  PCS_PROFESSIONALSKILLS_ENUM,
  PCS_SERVICEATTITUDE_ENUM,
  PCS_STRONGPOINTS_ENUM,
} from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

import WorkerModal from '../WorkerModal'

const EditDrawer = ({ row = {}, view = false }) => {
  const [form] = AekForm.useForm()
  const [detail, setDetail] = useState({})
  const { id } = row

  const selectWorker = async () => {
    const workers = await WorkerModal.PromiseThen()
    form.setFieldsValue({
      name: workers[0].fullName,
      phoneNo: workers[0].mobileNumber,
      departmentId: workers[0].departmentId,
    })
  }

  const getDetail = async () => {
    const { data } = await requestWithTry(getNursingWorkersApi, {
      id,
    })
    if (view) {
      setDetail({
        ...data,
        files: data.files?.map(({ fileUrl, fileName }) => ({ name: fileName, url: fileUrl })),
      })
    }
    form.setFieldsValue({
      ...data,
      files: data.files?.map(({ fileUrl, fileName }) => ({ name: fileName, url: fileUrl })),
    })
  }

  useEffect(() => {
    if (!id) return
    getDetail()
  }, [id])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData1 = [
    {
      field: 'name',
      label: '姓名',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
      other: <a onClick={selectWorker}>选择</a>,
    },
    {
      field: 'phoneNo',
      label: '手机号',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: { name: 'Input' },
    },
    {
      field: 'companionType',
      label: '陪护类型',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_COMPANION_TYPE_ENUM.options,
        },
      },
      viewRender: value => PCS_COMPANION_TYPE_ENUM.getText(value),
    },
    {
      field: 'companionWay',
      label: '陪护方式',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Select',
        props: {
          options: PCS_COMPANION_WAY_ENUM.options,
        },
      },
      viewRender: value => PCS_COMPANION_WAY_ENUM.getText(value),
    },
    {
      field: 'companionCompanyId',
      label: '陪护公司',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekSelect',
        props: {
          api: companionCompanyListApi,
        },
      },
      viewField: 'companionCompanyName',
    },
    {
      field: 'departmentId',
      label: '组织架构',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekTreeSelect',
        props: {
          api: queryOrgTreeApi,
          fieldNames: { value: 'departmentId', label: 'departmentName' },
        },
      },
      viewField: 'departmentName',
    },
    {
      field: 'account',
      label: '银行账户',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_CMB_DEBIT,
            message: '请输入正确的银行账户',
          },
        ],
      },
      component: { name: 'Input' },
    },
  ]

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData2 = [
    {
      field: 'professionalSkills',
      label: '专业技能',
      component: {
        name: 'CheckboxGroup',
        props: {
          options: PCS_PROFESSIONALSKILLS_ENUM.options,
        },
      },
      viewRender: value => value?.map(value => PCS_PROFESSIONALSKILLS_ENUM.getText(value)).join(', '),
    },
    {
      field: 'strongPoints',
      label: '擅长领域',
      component: {
        name: 'CheckboxGroup',
        props: {
          options: PCS_STRONGPOINTS_ENUM.options,
        },
      },
      viewRender: value => value?.map(value => PCS_STRONGPOINTS_ENUM.getText(value)).join(', '),
    },
    {
      field: 'serviceAttitude',
      label: '服务态度',
      component: {
        name: 'CheckboxGroup',
        props: {
          options: PCS_SERVICEATTITUDE_ENUM.options,
        },
      },
      viewRender: value => value?.map(value => PCS_SERVICEATTITUDE_ENUM.getText(value)).join(', '),
    },
  ]

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData3 = [
    {
      field: 'nursingCredentials',
      label: '基本资质',
      component: {
        name: 'CheckboxGroup',
        props: {
          options: PCS_NURSINGCREDENTIAL_ENUM.options,
        },
      },
      viewRender: value => value?.map(value => PCS_NURSINGCREDENTIAL_ENUM.getText(value)).join(', '),
    },
    {
      field: 'files',
      label: '证件资料',
      formItemProps: {
        help: '支持上传.rar;.zip;.doc;.docx;.pdf等文件和图片',
      },
      component: {
        name: 'AekUpload',
        props: { fileType: 'unset' },
      },
      viewRender: value => {
        return value?.length > 0 ? (
          <AekUpload
            limitFileNum={value?.length ?? 0}
            value={value}
            showUploadList={{
              showRemoveIcon: false,
            }}
          />
        ) : (
          '-'
        )
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      id,
      ...values,
      files: values.files?.map(({ url, name }) => ({ fileName: name, fileUrl: url })),
    }
    await requestWithTry(id ? updateNursingWorkersApi : createNursingWorkersApi, params)
  }

  return (
    <AekDrawer title={view ? '详情' : id ? '编辑' : '新增'} width='90%' onOk={onOk} showFooter={!view}>
      <APanel title='基本信息'>
        <AekForm allView={view} form={form} detail={detail} formData={formData1} col={8} />
      </APanel>
      <APanel title='擅长领域'>
        <AekForm allView={view} form={form} detail={detail} formData={formData2} />
      </APanel>
      <APanel title='资质证书'>
        <AekForm allView={view} form={form} detail={detail} formData={formData3} />
      </APanel>
    </AekDrawer>
  )
}

EditDrawer.PromiseThen = PromiseThen

export default EditDrawer
